import {
  Body,
  Controller,
  Delete,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Patch,
  Post,
  Query,
  Req,
} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { JwtNeed } from '@/common/decorator'
import {
  CompleteWheelTaskDto,
  CreateWheelTaskDto,
  ListPageWheelTaskDto,
  UpdateWheelTaskDto,
} from './dto/wheel-task.dto'
import { WheelTaskService } from './wheel-task.service'

@ApiTags('后台/二期/抽奖任务')
@Controller('admin/wheel_task')
export class WheelTaskController {
  constructor(private readonly wheelTaskService: WheelTaskService) {}

  /**
   * 任务列表
   */
  @Get()
  page(@Query() data: ListPageWheelTaskDto) {
    const { pageNo, pageSize, ...args } = data
    return this.wheelTaskService.findPage({
      pageNo,
      pageSize,
      where: args,
    })
  }

  /**
   * 创建任务
   */
  @Post()
  create(@Body() data: CreateWheelTaskDto) {
    return this.wheelTaskService.save(data)
  }

  /**
   * 修改任务
   */
  @Patch(':wheelTaskId')
  async update(@Param('wheelTaskId') wheelTaskId: number, @Body() data: UpdateWheelTaskDto) {
    const wheelTask = await this.wheelTaskService.findOne({ where: { wheelTaskId } })
    if (!wheelTask) {
      throw new HttpException('数据不存在', HttpStatus.NOT_FOUND)
    }
    await this.wheelTaskService.update(wheelTask.wheelTaskId, data)
  }

  /**
   * 修改状态
   */
  @Get('switch_enabled/:wheelTaskId')
  async switchEnabled(@Param('wheelTaskId') wheelTaskId: number) {
    const wheelTask = await this.wheelTaskService.findOne({ where: { wheelTaskId } })
    if (!wheelTask) {
      throw new HttpException('数据不存在', HttpStatus.NOT_FOUND)
    }

    await this.wheelTaskService.update(wheelTaskId, { isEnabled: !wheelTask.isEnabled })
  }

  /**
   * 删除任务
   */
  @Delete(':wheelTaskId')
  delete(@Param('wheelTaskId') wheelTaskId: number) {
    this.wheelTaskService.delete(wheelTaskId)
  }
}

@ApiTags('官网/二期/抽奖任务')
@Controller('web/wheel_task')
export class WebWheelTaskController {
  constructor(private readonly wheelTaskService: WheelTaskService) {}

  /**
   * 完成任务
   */
  @Post('complete_task')
  @JwtNeed()
  async completeTask(@Req() req: Request, @Body() data: CompleteWheelTaskDto) {
    return await this.wheelTaskService.completeTask(req.user.uid, data.wheelTaskId)
  }

  /**
   * 当前用户任务列表
   */
  @Get('user_task')
  @JwtNeed()
  async getTasks(@Req() req: Request) {
    if (!req.user.uid) {
      throw new HttpException('请先登录', HttpStatus.UNAUTHORIZED)
    }
    await this.wheelTaskService.upsertUserTask(req.user.uid)
    return await this.wheelTaskService.findUserTasks(req.user.uid)
  }
}
